<!DOCTYPE html>
<uieip type="page" value="login" debug="true" timeout="5000"></uieip>
<uieip type="reg" value="console"></uieip>

<html>

<head>
    <uieip type="file" value="inc" src="/yqwin/easyui/include.txt"></uieip>
    <uieip type="file" value="css" src="/yqwin/css/yqwin.min"></uieip>
    <uieip type="file" value="js" src="/yqwin/src/yqwin.min"></uieip>
    <title>MdiWin Demo - edit</title>
    <!-- 引入结束 -->
    <style>
        body {
            margin: 0px;
            overflow: hidden;
        }

        table {
            border-spacing: 0px;
        }

        table label {
            font-size: 14px;
        }

        table td {
            white-space: nowrap;
            overflow: hidden;
            /* 可选：隐藏溢出内容 */
            text-overflow: ellipsis;
            /* 可选：用省略号表示溢出内容 */
        }
    </style>
</head>

<body>
    <table id="tb_menu" style="width: 100%;">
        <tr>
            <td colspan="5"
                style="padding: 3px 0px 3px 7px;background-color: #f6f6f6;border-bottom-width: 1px;border-bottom-style: inset;border-bottom-color: lightgray;">
                <div id="menu_top"></div>
            </td>
        </tr>
    </table>
    <table id="tb_info">
        <tr>
            <td style="padding: 5px 0px 5px 12px;">
                <input id="txt_name" class="easyui-textbox"
                    data-options="label:'名称',labelPosition:'left',labelWidth:'35px',readonly:true" style="width:150px;">
            </td>
            <td style="padding: 5px 0px 5px 12px;">
                <input id="txt_describe" class="easyui-textbox"
                    data-options="label:'描述',labelPosition:'left',labelWidth:'35px,readonly:true'" style="width:210px;">
            </td>
            <td style="padding: 5px 0px 5px 12px;">
                <input id="txt_tb_name" class="easyui-textbox"
                    data-options="label:'实际表名',labelPosition:'left',labelWidth:'65px',readonly:true"
                    style="width:205px;">
            </td>
            <td style="padding: 5px 5px 5px 12px;">
                <label>存储过程</label>
            </td>
            <td>
                <div id="txt_proc"></div>
            </td>
        </tr>
    </table>
    <div id="div_editor" style="width: 100%;height: 400px;"></div>
    <input id="txt_openfile" type="file" accept=".sql" style="display: none;">
    <!-- <div id="tab_set" data-options="border:false" class="easyui-tabs" style="width:100%;height:250px;margin: 0px;">
        <div title="模板" style="padding:0px;display:none;">
            <table id="tb_ui"></table>
        </div>
    </div> -->
    <script>
        var dbname = $.urlRequest("dbname");
        var tbname = $.urlRequest("tbname");
        var tb_id = $.urlRequest("tb_id");

        hasRun = true;
        if (dbname == "" || tbname == "" || tb_id == "") {
            hasRun = false;
        }

        var tb_row = {}; //表信息
        function form_load() {
            $(window).resize(function () {
                onresize();
            });

            onresize();

            getTbRow(function (res) {
                if (res.error != 0) {
                    return;
                }

                tb_row = res.row;
                $("#txt_name").textbox("setValue", tb_row["name"]);
                $("#txt_describe").textbox("setValue", tb_row["describe"]);
                $("#txt_tb_name").textbox("setValue", tb_row["tb_name"]);
                //console.log(tb_row);

                var lists = [{
                    "id": "-1",
                    "text": "选择"
                }, {
                    "id": "add",
                    "text": "add"
                }, {
                    "id": "upp",
                    "text": "upp"
                }, {
                    "id": "del",
                    "text": "del"
                }];

                if (res.row.is_queue) {
                    lists.push({
                        "id": "move",
                        "text": "move"
                    });
                }

                if (res.row.is_tree) {
                    lists.push({
                        "id": "path",
                        "text": "path"
                    });

                    lists.push({
                        "id": "paste",
                        "text": "paste"
                    });
                }

                lists.push({
                    "id": "action",
                    "text": "action"
                });

                var $type = $("#menu_top").yqTopMenu("getBtn", "type");
                $type.combobox("loadData", lists);
                $type.combobox("setValue", "-1");

                $("#txt_proc").yqComboGrid("loadData");

                loadFileSet();
            });
        }

        function onresize() {
            var w = window.innerWidth;
            var h = window.innerHeight;
            //console.log($("#tb_menu").height() + $("#tb_info").height())
            h -= ($("#tb_menu").height() + $("#tb_info").height());

            $("#div_editor").yqCodeEdit("resize", {
                width: w,
                height: h
            });
        }

        $(function () {
            initTopMenu();
        });

        function initTopMenu() {
            $("#menu_top").yqTopMenu({
                menus: [
                    {
                        id: "type",
                        type: "combobox",
                        width: 150,
                        label: '模版类型',
                        labelPosition: 'left',
                        labelWidth: '65px',
                        valueField: 'id',
                        textField: 'text',
                        editable: false,
                        panelHeight: 'auto',
                        data: [{
                            "id": "-1",
                            "text": "选择"
                        }],
                        onChange: function (newValue, oldValue) {
                            getProcModel(newValue);
                        }
                    }, {
                        id: "get",
                        text: "获取模版",
                        iconCls: "icon2-down",
                        onClick: function () {
                            var $type = $("#menu_top").yqTopMenu("getBtn", "type");
                            var val = $type.combobox("getValue");
                            getProcModel(val);
                        }
                    }, {},
                    {
                        id: "save",
                        text: "保存",
                        iconCls: "icon2-save",
                        onClick: function () {
                            save();
                        }
                    }, {
                        id: "open",
                        text: "打开",
                        iconCls: "icon2-open",
                        onClick: function () {
                            $("#txt_openfile").click();
                        }
                    }, {
                        id: "upload",
                        text: "上传",
                        iconCls: "icon2-rs-upload",
                        onClick: function () {
                            SaveProcInfo();
                        }
                    }],
                afterBindingTitle: function () {
                    initProc();
                },
            });
        }

        function initProc() {
            $("#txt_proc").yqComboGrid({
                dbname: dbname,
                tbname: "sys_tb_proc",
                keyId: "sid",
                bindingKeyId: "tb_id",
                bindingValue: tb_id,
                width: 260,
                editMode: 1,
                editType: 1,
                editModeW: 400,
                editModeH: 250,
                editModeNo: -1,
                loadDefault: false,
                blankTag: "*",
                loadData: false,
                isEdit: true,
                isSeek: false,
                displayMember: "name",
                panelWidth: 400,
                panelHeight: 250,
                rownumbers: true,
                isPage: false,
                isEdit: true,
                move: true,
                editMenus: [{},
                {
                    id: "download",
                    text: "下载",
                    iconCls: "icon2-download",
                    onClick: function () {
                        var row = $("#txt_proc").yqComboGrid("getSelected")
                        if (!(row === null)) {
                            getProcInfo(row["name"]);
                        }
                    }
                }],
                afterBindingTitle: function () {
                    initEdit();
                },
                onChange: function (newValue, newRow, oldValue, oldRow) {
                    console.log("onChange",newValue, newRow, oldValue, oldRow);
                    if (newRow) {
                        getProcInfo(newRow["name"]);
                    }
                },
            });
        }

        function initEdit() {
            $("#div_editor").yqCodeEdit({
                types: ["sql"],
                type: "sql",
                value: `select * from aaaa;`,
                goDocEnd: false,
                afterBindingTitle: function () {
                    form_load();
                },
            });
        };

        function loadFileSet() {
            $("#txt_openfile").bind('change', function (e) {
                var file = e.target.files[0]; // 获取选中的文件  
                if (file) {
                    var regex = /\.sql$/;
                    if (regex.test(file.name)) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            try {
                                $("#div_editor").yqCodeEdit("setValue", e.target.result);
                            }
                            catch (err) {
                                console.error("filejson", err);
                                $.yqMessager("error", "内容格式错误。");
                            }

                            $("#txt_openfile").val("");
                        };
                        reader.readAsText(file);
                    }
                }
            });
        }

        function getTbRow(callback) {
            var opts = {
                dbname: dbname,
                tbname: "sys_tb",
                keyid: "sid",
                keyval: tb_id
            };

            $.yqDbTbRow(opts, function (res) {
                callback(res);
            });
        }

        //获取存储过程模版
        function getProcModel(_type) {
            $("#div_editor").yqCodeEdit("setValue", "");
            if (_type == "-1") {
                return;
            }

            $.yqProcModel({
                dbname: dbname,
                tbname: tb_row.name,
                actionval: _type
            }, function (res) {
                if (res.error == 0) {
                    $("#div_editor").yqCodeEdit("setValue", res.info);
                }
                //console.log(res);
            });
        }

        //获取存储过程
        function getProcInfo(name) {
            $("#div_editor").yqCodeEdit("setValue", "");
            $.yqProcInfo({
                dbname: dbname,
                procname: name
            }, function (res) {
                if (res.error == 0) {
                    $("#div_editor").yqCodeEdit("setValue", res.info);
                }
                //console.log(res);
            });
        }

        //获取存储过程
        function SaveProcInfo() {
            var proc = $("#div_editor").yqCodeEdit("getValue");
            $.yqProcSave({
                dbname: dbname,
                proc: proc
            }, function (res) {
                if (res.error == 0) {
                    $.yqMessager("success", "执行成功。");
                } else {
                    console.log(res);
                    $.yqMessager("error", res.info + "[" + res.error + "]");
                }
            });
        }

        //保存json
        function save() {
            var text = $("#div_editor").yqCodeEdit("getValue");

            var blob = new Blob([text], { type: "text/plain;charset=utf-8" });
            var url = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = url;

            var filename = tb_row["name"];
            var $type = $("#menu_top").yqTopMenu("getBtn", "type");
            var _type = $type.combobox("getValue");
            if (_type != "-1") {
                filename += "_" + _type;
            }
            filename += ".sql";

            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }


    </script>
</body>

</html>